import { Component, createRef } from 'react';
import './index.scss';
import logo from './images/logo.png';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import api from '../../api';
import storage from '../../utils/storage';

export default class Login extends Component {
  state = {
    loading: false,
  };
  formRef = createRef();
  render() {
    const { loading } = this.state;
    return (
      <div className='login'>
        <div className='header'>
          <img src={logo} alt='logo' />
          <h1>React项目：后台管理系统</h1>
        </div>
        <div className='content'>
          <div className='form-box'>
            <div className='title'>用户登录</div>
            <Form ref={this.formRef} onFinish={this.onFinish} initialValues={{ username: 'admin', password: 'admin' }}>
              <Form.Item name='username' rules={[{ validator: this.validUsername }]}>
                <Input placeholder='请输入用户名' prefix={<UserOutlined />} />
              </Form.Item>
              <Form.Item name='password' rules={[{ required: true, message: '密码不能为空！' }]}>
                <Input.Password placeholder='请输入密码' prefix={<LockOutlined />} className='pwd' />
              </Form.Item>
              <Form.Item>
                <Button type='primary' className='signIn' htmlType='submit' loading={loading}>
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    );
  }
  validUsername = (rule, val) => {
    if (!val) {
      return Promise.reject(new Error('请输入用户名'));
    }
    if (val.length < 4 || val.length > 10) {
      return Promise.reject(new Error('用户名长度在4到10之间'));
    }
    return Promise.resolve();
  };
  onFinish = async formData => {
    this.setState({ loading: true });
    const res = await api('login', formData);
    this.setState({ loading: false });
    if (res.status === 1) {
      message.error(res.msg);
    } else {      
      message.success('登录成功！')
      storage.setUser(res.data.username)
      this.props.history.replace('/')
    }
  };
}
